package com.itheima.service.impl;
import com.itheima.dao.AccountDao;
import com.itheima.pojo.Account;
import com.itheima.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;


import javax.sql.DataSource;

@Service
public class AccountServiceImpl implements AccountService {
    //数据装配
   @Autowired
    AccountDao accountDao;
    @Autowired
    DataSource dataSource;
    @Override
    public void transfer(String froName, String toName, double money) {
        ////获取账户信息
        //Account accountDaoForName = accountDao.findByName(froName);
        //Account accountDaoToName = accountDao.findByName(toName);
        ////开始转账业务
        //accountDaoForName.setMoney(accountDaoForName.getMoney()-money);
        //accountDaoToName.setMoney(accountDaoToName.getMoney()+money);
        //accountDao.update(accountDaoForName);
        ////System.out.println(1/0);
        //accountDao.update(accountDaoToName);
        //创建事务管理器对象
        PlatformTransactionManager platformTransactionManager = null;
        //创建事务详情对象
        TransactionDefinition transactionDefinition = null;
        //事务状态对象
        TransactionStatus transactionStatus = null;
        try {
            transactionDefinition = new DefaultTransactionDefinition();
            //必须携带数据源
            platformTransactionManager = new DataSourceTransactionManager(dataSource);
            //开启事务
            transactionStatus = platformTransactionManager.getTransaction(transactionDefinition);
            //根据名称获取用户信息
            Account fromAccount = accountDao.findByName(froName);
            Account toAcconut = accountDao.findByName(toName);
            //开始转装的业务
            fromAccount.setMoney(fromAccount.getMoney() - money);
            toAcconut.setMoney(fromAccount.getMoney() + money);
            //更新数据库
            accountDao.update(fromAccount);
            //System.out.println(1 / 0);
            accountDao.update(toAcconut);
            //事务提交
            platformTransactionManager.commit(transactionStatus);
        } catch (Exception e) {

            //如果出现异常事务回滚
            platformTransactionManager.rollback(transactionStatus);
            e.printStackTrace();
        }
    }
}
